import { createRouter, createWebHistory } from 'vue-router'
import { constantRoute } from './routes'
import { useUserStore } from '@/stores/modules/user'
import setting from '@/setting'
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: constantRoute,
  //滚动行为
  scrollBehavior() {
    return {
      left: 0,
      top: 0
    }
  }
})

// 路由前置守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  // 路由权限鉴权
  if (to.matched.some((r) => r.meta?.requiresAuth)) {
    if (!userStore.token) {
      next({ name: 'login', query: { redirect: to.fullPath } })
      return
    }
  }
  // 已登录用户 不能再重复登录
  if (to.path === '/login' && userStore.token) {
    next({ path: '/' })
    return
  }
  // 页面加载进度条
  nprogress.start()
  // 修改页面标题
  document.title = `${setting.title}-${to.meta.title}`
  next()
})

// 路由后置守卫
router.afterEach(() => {
  nprogress.done()
})

export default router
